from django.contrib.auth.models import User
from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator
from django.utils import timezone


# 用户信息
class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    likes = models.ManyToManyField('Music', blank=True, related_name='like_users')
    dislikes = models.ManyToManyField('Music', blank=True, related_name='dislike_users')
    first_run = models.BooleanField('是否第一次运行,执行冷启动策略', default=True)
    genre_subscribe = models.TextField('流派订阅', blank=True)
    language_subscribe = models.TextField('语言订阅', blank=True)

    def __str__(self):
        return self.user.username

    class Meta:
        verbose_name = '用户信息'
        verbose_name_plural = verbose_name


# 音乐
class Music(models.Model):
    song_name = models.CharField('歌曲名称', max_length=1000)
    song_length = models.IntegerField('歌曲长度 单位为ms')
    genre_ids = models.CharField('歌曲流派', max_length=100)
    artist_name = models.CharField('歌手', max_length=1000)
    composer = models.CharField('作曲', max_length=1000)
    lyricist = models.CharField('作词', max_length=1000)
    language = models.CharField('语种', max_length=20)
    url = models.CharField('歌曲链接', max_length=1000, default="https://m701.music.126.net/20240301234259/3c4c6553837086cd21eb6013475d9d05/jdymusic/obj/wo3DlMOGwrbDjj7DisKw/27978919250/663c/4088/7b7a/0c48207cb013f953f46fe2da7dd7f803.mp3")

    # 添加平均评分字段，用于缓存评分结果提高性能
    average_rating = models.FloatField('平均评分', default=0.0)
    rating_count = models.IntegerField('评分数量', default=0)

    def update_average_rating(self):
        """更新歌曲的平均评分"""
        ratings = self.ratings.all()
        if ratings:
            total = sum(rating.score for rating in ratings)
            self.average_rating = total / len(ratings)
            self.rating_count = len(ratings)
        else:
            self.average_rating = 0.0
            self.rating_count = 0
        self.save()

    def __str__(self):
        return self.song_name

    class Meta:
        verbose_name = '音乐信息'
        verbose_name_plural = verbose_name


# 音乐评分
class Rating(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='ratings')
    music = models.ForeignKey(Music, on_delete=models.CASCADE, related_name='ratings')
    score = models.IntegerField('评分', validators=[MinValueValidator(1), MaxValueValidator(5)])
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)

    class Meta:
        verbose_name = '音乐评分'
        verbose_name_plural = verbose_name
        # 确保用户对每首歌只能有一条评分记录
        unique_together = ('user', 'music')


# 音乐评论
class Comment(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='comments')
    music = models.ForeignKey(Music, on_delete=models.CASCADE, related_name='comments')
    content = models.TextField('评论内容')
    created_at = models.DateTimeField('创建时间', default=timezone.now)
    
    # 添加父评论字段用于实现评论回复功能
    parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='replies')
    
    class Meta:
        verbose_name = '音乐评论'
        verbose_name_plural = verbose_name
        ordering = ['-created_at']  # 按时间降序排列

    def __str__(self):
        return f"{self.user.username}对{self.music.song_name}的评论"


# 播放历史记录
class PlayHistory(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='play_histories', verbose_name='用户')
    music = models.ForeignKey(Music, on_delete=models.CASCADE, related_name='play_histories', verbose_name='音乐')
    played_at = models.DateTimeField('播放时间', auto_now_add=True)
    
    class Meta:
        verbose_name = '播放历史'
        verbose_name_plural = verbose_name
        ordering = ['-played_at']  # 按播放时间降序排列
    
    def __str__(self):
        return f"{self.user.username}播放{self.music.song_name}于{self.played_at.strftime('%Y-%m-%d %H:%M')}"
